package com.start.pay.core.quartz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.start.pay.core.StartGlobalPayConfig;
import com.start.pay.core.entity.StartPayOrderEntity;
import com.start.pay.core.enums.StartPayState;
import com.start.pay.core.event.GlobalStartPayOrderEventDispatcher;
import com.start.pay.core.service.StartPayOrderService;
import com.start.quartz.scheduling.StartQuartzJobBean;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

public class StartGlobalPayQuartz extends StartQuartzJobBean {
    @Autowired
    private StartPayOrderService startPayOrderService;
    @Autowired
    private StartGlobalPayConfig startGlobalPayConfig;

    /**
     * 任务执行
     *
     * @param jobExecutionContext 任务上下文环境
     * @param jobDataMap          任务数据
     */
    @Override
    protected void executeTask(JobExecutionContext jobExecutionContext, JobDataMap jobDataMap) {
        LocalDateTime now = LocalDateTime.now();
        List<StartPayOrderEntity> list = startPayOrderService.list(new LambdaQueryWrapper<StartPayOrderEntity>().eq(StartPayOrderEntity::getPayState, StartPayState.UN_PAY).ge(StartPayOrderEntity::getExpireTime, now));
        if (list.isEmpty()) {
            return;
        }
        GlobalStartPayOrderEventDispatcher dispatcher = GlobalStartPayOrderEventDispatcher.getInstance();
        for (StartPayOrderEntity entity : list) {
            entity.setPayState(StartPayState.ORDER_CLOSE.getValue());
            startPayOrderService.updateById(entity);
            dispatcher.onOrderClose(entity);
        }

    }
}
